#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time    : 2022/1/5 15:16
# @Author  : liuhuan7
# @email   : liuhuan7@staff.sina.com.cn
# @File    : get_image_tag.py
# @Software: PyCharm

import requests
import json
import sys

class Harbor(object):
    """harbor镜像仓库操作类

    """

    def __init__(self, username, passwrod, url):
        self.url = url
        self.s = requests.session()
        self.s.auth = (username, passwrod)

    def get_projects(self):
        """获取项目列表

        :return: list
        """
        url = self.url + "/api/projects"
        res = self.s.get(url=url)
        return res.json()

    def get_repositories(self, project_id, page=1, page_size=10):
        """获取仓库列表

        :param project_id: 项目id
        :param page: 页数
        :param page_size: 每页大小
        :return: list
        """
        url = self.url + "/api/repositories?project_id=%d&page=%d&page_size=%d" % (project_id, page, page_size)
        res = self.s.get(url=url)
        return res.json()

    def get_tags(self, repo_name):
        """获取镜像的tags

        :param repo_name: 镜像名称
        :return: list
        """
        url = self.url + "/api/repositories/%s/tags" % repo_name
        res = self.s.get(url=url)
        return res.json()


def main():
    with open('./config/harbor.json', 'r') as f:
        load_f = json.load(f)
    H = Harbor(username=load_f['username'], passwrod=load_f['password'], url=load_f['url'])
    projects = H.get_projects()
    image_name = sys.argv[1]
    for p in projects:
        # print("### project_id: %d, project_name: %s" % (p['project_id'], p['name']))
        if p['name'] != 'finance':
            continue
        page = 1
        page_size = 50
        while True:
            repositories = H.get_repositories(project_id=p['project_id'], page=page, page_size=page_size)
            for repositorie in repositories:
                if repositorie['name'] == image_name:
                    repo_tags = H.get_tags(repo_name=repositorie['name'])
                    repo_tags.sort(key=lambda x: x['created'], reverse=True)
                    repo_tag_list = [tag['name'] for tag in repo_tags if tag['name'] != 'latest']
                    print(repo_tag_list[1])
                    break
            else:
                count = page * page_size
                if count < p['repo_count']:
                    page += 1
                    continue
                else:
                    break
            break


if __name__ == '__main__':
    main()
